package com.lovo.bbs.servlet.admin;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.lovo.bbs.bo.ForumBo;
import com.lovo.bbs.bo.ForumStatBo;
import com.lovo.bbs.bo.PostBo;
import com.lovo.bbs.bo.TopicBo;
import com.lovo.bbs.vo.ForumStatVo;
import com.lovo.bbs.vo.ForumVo;
import com.lovo.bbs.vo.PostVo;

/**
 * 管理回帖的Servlet
 * 
 * @author tiancen2001
 * 
 */
public class PostUpdateServlet extends HttpServlet {
	private static final long serialVersionUID = 8505623208549652411L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		this.doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest request, HttpServletResponse resp)
			throws ServletException, IOException {
		
		int opType = 0;//操作类型
		if (request.getParameter("opType") != null)
			opType = Integer.parseInt(request.getParameter("opType"));
		
		
		// 原页码,返回原页面时使用
		int queryPage = Integer.parseInt(request.getParameter("queryPage"));
		if (queryPage == 0) {
			queryPage = 1;
		}
		
		int postid = Integer.parseInt(request.getParameter("postid"));//回帖ID
		String postTilte = new String(request.getParameter("posttopic")
				.getBytes("ISO-8859-1"), "utf-8");//回帖标题

		
		int topicid =  Integer.parseInt(request.getParameter("topicid"));//回帖所属主题ID
        
		PostVo vo = new PostVo();
		vo.setPostid(postid);
		vo.setPosttitle(postTilte);

		
		int dataChanged = 0;
		ServletContext context = request.getSession().getServletContext();
		
		ForumBo forumBo = new ForumBo();
		ForumStatBo forumStatBo = new ForumStatBo();
		PostBo postBo = new PostBo();
		TopicBo topicBo = new TopicBo();
		if(opType==2){//修改回帖
			dataChanged=postBo.updatePost(vo, PostBo.OPER_OF_UPDATE);
		}else if(opType==3){//删除回帖
			//找到该回复所在的论坛
			int forumid = postBo.getForumIDByPostID(postid);
			//刷新该论坛的统计数据
			forumBo.delOnePost(forumid);
			
			dataChanged=postBo.updatePost(vo, PostBo.OPER_OF_DELETE);
			//更新网站信息数据库
			dataChanged = forumStatBo.reset();
			
			//更新主题信息
			//主题回复数减一
			topicBo.delOnePost(topicid);
			//重新计算主题最后回复
			topicBo.setLastPost(topicid);
			
			//更新内存数据
			// 取得所有论坛列表
			ArrayList<ForumVo> forumList = forumBo.getAllForum();
			// 更新论坛列表
			context.setAttribute("forumList", forumList);
			// 更新论坛MAP
			context.setAttribute("forumMap", forumBo.getForumMap(forumList));
		}
		
		if (opType == 3) {// 如果是删除回帖,则同时更新......
			// 更新网站杂项信息
			ForumStatVo forumInfo = forumStatBo.getForumInfo();
			context.setAttribute("forumInfo", forumInfo);
		}
		
		if (dataChanged == 1) {
			resp
					.sendRedirect("postManageQueryPage.jsp?queryPage="
							+ queryPage);
		}
		
	}

}
